﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

using MASAS.MSM.SharePoint.REST.Config;

namespace MASAS.MSM.SharePoint.REST.Utils
{

    /// <summary>
    /// Class ClientContext.
    /// </summary>
    internal class ClientContext
    {

        /// <summary>
        /// Gets or sets the form digest.
        /// </summary>
        /// <value>The form digest.</value>
        internal string FormDigest { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ClientContext"/> class.
        /// </summary>
        /// <param name="scData">The sc data.</param>
        internal ClientContext( SiteConfigData scData )
        {
            string response = "";

            response = SPHelper_REST.PostData( scData.Url + "/_api/contextinfo", "", scData );

            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            Dictionary<string, object> root = jsSerializer.Deserialize<Dictionary<string, object>>( response );

            object tempObject;
            if( root != null && root.TryGetValue( "d", out tempObject ) && tempObject is Dictionary<string, object> )
            {
                Dictionary<string, object> data = tempObject as Dictionary<string, object>;

                if( data.TryGetValue( "GetContextWebInformation", out tempObject ) )
                {
                    Dictionary<string, object> contextInfo = tempObject as Dictionary<string, object>;

                    if( contextInfo.TryGetValue( "FormDigestValue", out tempObject ) )
                    {
                        this.FormDigest = tempObject as string;
                    }
                }
                
            }
        }

    }

}
